from typing import Any, Dict, Optional, Tuple
from decimal import Decimal
from datetime import datetime
from langchain.tools import BaseTool, tool
import json
from .database_manager import DatabaseManager
from .database_tool import DatabaseTool
from .nlp_tool import NLPTool
import re


class InventoryTool(BaseTool):
    name = "库存管理工具"
    description = "用于管理商品库存的工具"
    db_manager: DatabaseManager = None
    db_tool: DatabaseTool = None
    nlp_tool: NLPTool = None
    current_transaction: Dict[str, Any] = None

    def __init__(self, db_tool: DatabaseTool, nlp_tool: NLPTool, **data):
        super().__init__(**data)
        self.db_manager = DatabaseManager()
        self.db_tool = db_tool
        self.nlp_tool = nlp_tool

    def _run(self, command: str) -> Any:
        """实现BaseTool的抽象方法"""
        try:
            if command.startswith("check:"):
                product_name = command.split(":")[1]
                return self.tool(product_name, 1, "check")
            elif command.startswith("update:"):
                _, product_name, quantity = command.split(":")
                return self.tool(product_name, int(quantity), "update")
            return "无效的命令格式"
        except Exception as e:
            return f"执行命令错误: {str(e)}"

    def _arun(self, command: str) -> Any:
        """实现BaseTool的异步抽象方法"""
        raise NotImplementedError("暂不支持异步操作")

    @tool("检查和更新库存")
    def tool(self, product_name: str, quantity: int, operation: str = "check"):
        """
        检查和更新库存的工具
        参数:
            product_name: 商品名称
            quantity: 数量
            operation: 操作类型，可以是"check"(检查)或"update"(更新)
        """
        try:
            # 查询商品信息
            results = self.db_manager.execute_query(
                "SELECT * FROM products WHERE name LIKE %s",
                (f"%{product_name}%",)
            )

            if not results:
                return json.dumps({"status": "error", "message": f"未找到商品: {product_name}"}, ensure_ascii=False)

            product = results[0]

            if operation == "check":
                if product['stock'] >= quantity:
                    return json.dumps({
                        "status": "success",
                        "message": f"库存充足",
                        "data": {
                            "product_id": product['id'],
                            "current_stock": product['stock'],
                            "price": product['price']
                        }
                    }, ensure_ascii=False)
                else:
                    return json.dumps({
                        "status": "insufficient",
                        "message": f"库存不足",
                        "data": {
                            "product_id": product['id'],
                            "current_stock": product['stock'],
                            "missing": quantity - product['stock']
                        }
                    }, ensure_ascii=False)

            elif operation == "update":
                if product['stock'] >= quantity:
                    new_stock = product['stock'] - quantity
                    self.db_manager.execute_update(
                        "UPDATE products SET stock = %s WHERE id = %s",
                        (new_stock, product['id'])
                    )

                    # 记录库存变化
                    self.db_manager.execute_update(
                        """INSERT INTO inventory 
                        (product_id, change_type, change_quantity, operator) 
                        VALUES (%s, %s, %s, %s)""",
                        (product['id'], 'Out', quantity, 'system')
                    )

                    return json.dumps({
                        "status": "success",
                        "message": f"库存更新成功",
                        "data": {
                            "product_id": product['id'],
                            "new_stock": new_stock
                        }
                    }, ensure_ascii=False)
                else:
                    return json.dumps({
                        "status": "error",
                        "message": f"库存不足，无法更新"
                    }, ensure_ascii=False)

        except Exception as e:
            return json.dumps({
                "status": "error",
                "message": f"操作失败: {str(e)}"
            }, ensure_ascii=False)

    def process_purchase(self, product_id: int, quantity: int, payment_method: str, coupon_id: Optional[int] = None) -> Tuple[bool, str, float]:
        """处理购买请求"""
        try:
            # 先检查库存是否充足
            stock_info = self.db_tool.check_stock(product_id)
            if not stock_info:
                return False, "商品不存在", 0.0
            
            if stock_info['stock'] < quantity:
                return False, f"库存不足，当前库存: {stock_info['stock']}", 0.0

            # 先处理支付
            payment_success, total_amount = self.db_tool.process_payment(
                product_id=product_id,
                quantity=quantity,
                payment_method=payment_method,
                coupon_id=coupon_id
            )

            if not payment_success:
                return False, "支付处理失败", 0.0

            # 支付成功后更新库存
            stock_update_success = self.db_tool.update_stock(
                product_id=product_id,
                quantity=quantity,
                change_type='Out',
                operator=f"购买-{payment_method}"
            )

            if not stock_update_success:
                # 如果库存更新失败，需要回滚支付
                # TODO: 实现支付回滚逻辑
                return False, "库存更新失败", 0.0

            return True, "购买成功", total_amount

        except Exception as e:
            error_msg = str(e)
            print(f"处理购买请求时出错: {error_msg}")
            return False, f"购买失败: {error_msg}", 0.0

    def process_payment(self, query: str) -> Dict[str, Any]:
        """处理支付请求"""
        try:
            if not self.current_transaction:
                return {
                    "success": False,
                    "message": "没有待支付的订单",
                    "data": None
                }

            # 解析支付方式
            valid, payment_method = self.nlp_tool.parse_payment_method(query)
            if not valid:
                return {
                    "success": False,
                    "message": "不支持的支付方式，请选择：现金/信用卡/移动支付",
                    "data": None
                }

            try:
                # 处理每个商品的支付
                for product in self.current_transaction["products"]:
                    success, amount = self.db_tool.process_payment(
                        product["product_id"],
                        int(product["quantity"]),
                        payment_method
                    )
                    
                    if not success:
                        raise Exception(f"商品 {product['product_name']} 支付处理失败")

                # 生成支付成功响应
                response = self.nlp_tool.generate_response("purchase_success", {
                    "products": self.current_transaction["products"],
                    "total_amount": self.current_transaction["total_amount"],
                    "payment_method": payment_method
                })

                # 清除当前交易
                transaction_data = self.current_transaction
                self.current_transaction = None

                return {
                    "success": True,
                    "message": response,
                    "data": transaction_data
                }

            except Exception as e:
                error_msg = str(e)
                print(f"支付处理出错: {error_msg}")
                return {
                    "success": False,
                    "message": f"支付失败: {error_msg}",
                    "data": None
                }

        except Exception as e:
            print(f"处理支付请求时出错: {str(e)}")
            return {
                "success": False,
                "message": "处理支付请求时出现错误",
                "data": None
            }

    def get_low_stock_alerts(self, threshold: int = 10) -> Dict[str, Any]:
        """获取库存预警"""
        try:
            low_stock_products = self.db_tool.get_low_stock_products(threshold)
            if not low_stock_products:
                return {
                    "success": True,
                    "message": "所有商品库存充足",
                    "data": []
                }

            # 构建预警信息
            alerts = []
            for product in low_stock_products:
                category = product["category_name"]
                unit = self.nlp_tool.category_units.get(category, "件")
                alerts.append(f"{product['name']}: 当前库存{product['stock']}{unit}")

            return {
                "success": True,
                "message": f"发现{len(alerts)}个库存不足的商品：\n" + "\n".join(alerts),
                "data": low_stock_products
            }

        except Exception as e:
            print(f"获取库存预警时出错: {str(e)}")
            return {
                "success": False,
                "message": "获取库存预警时出现错误",
                "data": None
            }

    def handle_purchase_intent(self, query: str) -> Dict[str, Any]:
        """处理用户的购买意图"""
        try:
            # 解析购买意图
            intent = self.nlp_tool.parse_purchase_intent(query)
            
            # 如果解析失败或没有商品信息
            if not intent.get('success') or not intent.get('items'):
                message = "无法识别要购买的商品。\n\n"
                message += "正确的购买格式是：用[支付方式]购买[数量][单位][商品名]。\n"
                message += "例如：用现金购买10斤苹果和5斤香蕉\n"
                message += "支持的支付方式：现金、信用卡、移动支付"
                return {
                    "success": False,
                    "message": message,
                    "data": None
                }
            
            # 存储成功处理的商品
            success_products = []
            total_amount = Decimal('0.0')
            
            # 检查所有商品是否可用
            for item in intent['items']:
                # 获取商品信息
                products = self.db_tool.get_product_by_name(item['product_name'])
                if not products:
                    return {
                        "success": False,
                        "message": f"未找到商品: {item['product_name']}",
                        "data": None
                    }
                
                product = products[0]  # 取第一个匹配的商品
                
                # 检查库存
                if product['stock'] < item['quantity']:
                    return {
                        "success": False,
                        "message": f"{product['name']}库存不足，当前库存: {product['stock']}{item['unit']}",
                        "data": None
                    }
                
                # 计算商品总价
                item_total = Decimal(str(product['price'])) * Decimal(str(item['quantity']))
                total_amount += item_total
                
                # 添加到成功处理列表
                success_products.append({
                    "product_id": product['id'],
                    "product_name": product['name'],
                    "quantity": item['quantity'],
                    "unit": item['unit'],
                    "price": float(product['price']),
                    "amount": float(item_total)
                })
            
            # 如果没有指定支付方式，返回友好提示
            if not intent.get('payment_method') or intent.get('payment_confidence', 0) < 0.7:
                message = "您需要说明支付方式。\n\n"
                message += "正确的购买格式是：用[支付方式]购买[数量][单位][商品名]。\n"
                message += "例如：用现金购买10斤苹果和5斤香蕉\n"
                message += "支持的支付方式：现金、信用卡、移动支付\n\n"
                
                if success_products:
                    message += "您的购物清单：\n"
                    for product in success_products:
                        message += f"- {product['quantity']}{product['unit']}{product['product_name']}，单价：{product['price']}元/{product['unit']}\n"
                    message += f"\n总金额：{float(total_amount)}元\n"
                    message += "\n请完整描述您的购买意图，包含支付方式。"
                
                # 保存当前交易信息
                self.current_transaction = {
                    "products": success_products,
                    "total_amount": float(total_amount)
                }
                
                return {
                    "success": False,
                    "message": message,
                    "data": None
                }
            
            # 如果指定了支付方式，处理支付和库存更新
            try:
                # 再次检查所有商品的库存
                for product in success_products:
                    current_stock = self.db_tool.check_stock(product["product_id"])
                    if current_stock['stock'] < product['quantity']:
                        return {
                            "success": False,
                            "message": f"{product['product_name']}库存不足，当前库存: {current_stock['stock']}{product['unit']}",
                            "data": None
                        }
                
                # 处理每个商品的支付和库存更新
                for product in success_products:
                    # 更新库存
                    stock_update_success = self.db_tool.update_stock(
                        product["product_id"],
                        int(product["quantity"]),
                        "Out",
                        "收银员"
                    )
                    
                    if not stock_update_success:
                        raise Exception(f"商品 {product['product_name']} 库存更新失败")
                    
                    # 处理支付
                    success, amount = self.db_tool.process_payment(
                        product["product_id"],
                        int(product["quantity"]),
                        intent['payment_method']
                    )
                    
                    if not success:
                        raise Exception(f"商品 {product['product_name']} 支付处理失败")
                
                # 生成支付成功响应
                response = self.nlp_tool.generate_response("purchase_success", {
                    "products": success_products,
                    "total_amount": float(total_amount),
                    "payment_method": intent['payment_method']
                })
                
                # 清除当前交易
                self.current_transaction = None
                
                return {
                    "success": True,
                    "message": response,
                    "data": {
                        "products": success_products,
                        "total_amount": float(total_amount),
                        "payment_method": intent['payment_method'],
                        "payment_status": "completed"
                    }
                }
                
            except Exception as e:
                error_msg = str(e)
                print(f"处理支付和库存更新时出错: {error_msg}")
                return {
                    "success": False,
                    "message": f"处理失败: {error_msg}",
                    "data": None
                }
                
        except Exception as e:
            print(f"处理购买请求时出错: {str(e)}")
            return {
                "success": False,
                "message": "无法识别要购买的商品。\n\n正确的购买格式是：用[支付方式]购买[数量][单位][商品名]。\n例如：用现金购买10斤苹果和5斤香蕉\n支持的支付方式：现金、信用卡、移动支付",
                "data": None
            }
